//
//  WBRefreshController.swift
//  JLWeibo
//
//  Created by sunjinliang on 15/12/14.
//  Copyright © 2015年 sunjinliang. All rights reserved.
//

import UIKit
import SnapKit

let WBRefreshControllerOffSet: CGFloat = -60
class WBRefreshController: UIRefreshControl {
    lazy var refreshView: WBRefreshView = WBRefreshView.refresView()
   override  func beginRefreshing() {
        super.beginRefreshing()
         refreshView.startAnimation()
    }
    override func endRefreshing() {
        super.endRefreshing()
        refreshView.stopAnimation()
    }
    override init() {
        super.init()
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init()
         setupUI()
    }
    
    func setupUI(){
        tintColor = UIColor.clearColor()
        addSubview(refreshView)
        refreshView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX)
            make.centerY.equalTo(self.snp_centerY)
            make.size.equalTo(refreshView.bounds.size)
        }
    }
    override var frame: CGRect {
        didSet{
            if frame.origin.y > 0 {
                return
            }
            if frame.origin.y < WBRefreshControllerOffSet && !refreshView.isUp{
                refreshView.isUp = true
            }
            else if frame.origin.y >= WBRefreshControllerOffSet && refreshView.isUp{

                refreshView.isUp = false
            }
        }
    }

    
}
class WBRefreshView: UIView {
    var isUp :Bool = false {
        didSet{
            tipIconViewRotation()
        }
    }
    @IBOutlet weak var loadIconView: UIImageView!
    @IBOutlet weak var tipView: UIView!
    @IBOutlet weak var tipIconView: UIImageView!
    class func refresView()->WBRefreshView{
        let nib = UINib(nibName: "WBRefreshView", bundle: nil)
        return nib.instantiateWithOwner(nil, options: nil)[0] as! WBRefreshView
    }
    func startAnimation(){
        let key = "transform.rotation"
        if  loadIconView.layer.animationForKey(key) != nil {
            return
        }
        tipView.hidden = true
        let anim = CABasicAnimation(keyPath: key)
        anim.toValue = 2 * M_PI
        anim.repeatCount = MAXFLOAT
        anim.duration = 2
        anim.removedOnCompletion = false
        loadIconView.layer.addAnimation(anim, forKey: key)
    }
    func stopAnimation(){
        tipView.hidden = false
        loadIconView.layer.removeAllAnimations()
    }
    /// 旋转箭头
    func tipIconViewRotation(){
        var angle: CGFloat = CGFloat(M_PI)
        angle += isUp ? -0.00001: 0.00001
        UIView.animateKeyframesWithDuration(0.2, delay: 0, options: [], animations: { () -> Void in
            self.tipIconView.transform = CGAffineTransformRotate(self.tipIconView.transform, angle)
            
            }, completion: nil)
    }

}